import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from "vue-router"
import {
  getUserInfo
} from '@/utils/storage.ts'
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/LoginView.vue'),
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/HomeView.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '/index',
        name: 'index',
        component: () => import('@/views/index/index.vue'),
      }
    ]
  },
  // 404 页面路由
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('@/views/NotFoundView.vue'),
  },
]
const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

router.beforeEach((to, from, next) => {
  console.log(to,from, 'beforeEach')
  const userInfo = getUserInfo()
  console.log(userInfo,userInfo?.token, 'userInfo')
  
  // 判断页面是否需要认证
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  
  // 如果页面需要认证但用户未登录，则跳转到登录页
  if (requiresAuth && (!userInfo || !userInfo.token)) {
    next('/login')
  } 
  // 判断用户是否已登录且要跳转到登录页
  else if (userInfo && userInfo.token && to.path === '/login') {
    // 已登录状态下阻止跳转到登录页，重定向到首页
    next('/index')
  } else {
    // 其他情况正常跳转
    next()
  }

})

export default router
